const { join } = require('path')
const exec = require('child_process').exec

const autoDotnetEf = (rootPath, { project, entity }) => {
	if (entity.autoMigration) {
		const { migrationName } = entity
		const { dbMigrationsPath, hostPath, corePath, coreSrcPath } = project
		const projectPath = join(rootPath, corePath, coreSrcPath)

		const migrtionShell = `dotnet ef migrations add "${migrationName}" -p ${join(projectPath, dbMigrationsPath, dbMigrationsPath)}.csproj -s ${join(projectPath, hostPath, hostPath)}.csproj`

		exec(migrtionShell, { encoding: 'utf-8' }, (err) => {
			if (err) {
				console.log('❗❗❗', `The name "${migrationName}" is used by an existing migration`.red)
			} else {
				console.log('⏰ dotnet-ef', `add migration`.yellow, `"${migrationName}"`.green, 'to', `${dbMigrationsPath}.csproj`.underline)

				// 更新数据库 database
				if (entity.updateDatabase) {
					const datbaseShell = `dotnet ef database update -p ${join(projectPath, dbMigrationsPath, dbMigrationsPath)}.csproj -s ${join(projectPath, hostPath, hostPath)}.csproj`
					exec(datbaseShell, { encoding: 'utf-8' }, (err, stdout) => {
						if (err) {
							console.log('❗❗❗', stdout.red)
						} else {
							console.log('⏰ dotnet-ef', `update database`.yellow, 'applying migration ', `"${migrationName}"`.green, 'success')
						}
					})
				}
			}
		})
	}
}

module.exports = {
	autoDotnetEf,
}
